import FullPathData from "../../eventbus/FullPathData.js";
import SaveManager from "./SaveManager.js";

class FunctionSaveFactory {

    static setWindow(win) {
        window = win;
    }

    static getWindow() {
        return FullPathData.window
    }

    static FunctionDump(function_handler, function_body, saveManager) {
        if (!saveManager){
            saveManager = new SaveManager(this.getWindow())
        }
        const serializedFunction = function_body.toString(); // 转换函数为字符串
        saveManager.save_data(function_handler, serializedFunction)
        console.log(`Stored function under handler: ${function_handler}`);

    }

    static FunctionLoad(function_handler, saveManager=null) {
        if (!saveManager) {
            saveManager = new SaveManager(this.getWindow())
        }
        try {
            const functionString = saveManager.load_data(function_handler);

            if (functionString) {
                return new Function(`return (${functionString})`)(); // 使用 new Function 创建函数
            } else {
                console.warn(`No function found for handler: ${function_handler}`);
                return null;
            }
        } catch (error) {
            console.error("Failed to load function: ", error);
            return null;
        }
    }
}


export default FunctionSaveFactory;